package com.starinside.wp.handler;


import com.alibaba.fastjson.JSON;
import com.starinside.wp.builder.TextBuilder;
import com.starinside.wp.components.redis.RedisService;
import com.starinside.wp.service.chat.IQuestionService;
import com.unfbx.chatgpt.entity.chat.Message;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceHttpClientImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@Slf4j
public class MsgHandler extends AbstractHandler {

    @Autowired
    private RedisService redisService;

    @Qualifier("XFSQuestionServiceImpl")
//    @Qualifier("GLMQuestionServiceImpl")
//    @Qualifier("GPTQuestionServiceImpl")
    @Autowired
    private IQuestionService questionService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

        //组装回复消息
        Map<String, Object> allFields = wxMessage.getAllFieldsMap();
        String content = (String) allFields.get("Content");

        if (StringUtils.isBlank(content)){
            content = (String)allFields.get("Recognition");
        }

        if (StringUtils.isBlank(content)){
            log.debug("return null by null content");
            return null;
        }

        String fromUserName = (String) allFields.get("FromUserName");

        JSON.toJSON("------------------------开始对话-------------------------"+wxMessage);
//        System.out.println("current thread" + Thread.currentThread());

        if (content.startsWith("重新开始") ){
            redisService.deleteLike(fromUserName);
            return new TextBuilder().build("对话已经重新开始,请输入内容。", wxMessage, weixinService);
        }else {
           return replyWithKefuMessageStream(weixinService, fromUserName, content, wxMessage, weixinService);
        }
    }

//    @Async
//    protected void replyWithKefuMessage(WxMpService weixinService, String fromUserName, String message){
//        log.debug("return null");
//
//        CompletionResponse completions = openAiClient.completions(message);
//        String result = Arrays.stream(completions.getChoices())
//                .map(o->o.getText())
//                .map(o->o.trim())
//                .filter(o->StringUtils.isNotBlank(o))
//                .collect(Collectors.joining());
//
//
//        WxMpKefuMessage kefuMessage = WxMpKefuMessage.TEXT()
//                .content(result).toUser(fromUserName).build();
//
//        log.debug("kefu message {}:{}", fromUserName, result);
//        try {
//            weixinService.getKefuService().sendKefuMessage(kefuMessage);
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//        }
//        log.debug("kefu finish");
//    }
//
//    @Async
//    protected void replyWithKefuImageMessageStream(WxMpService mpService, String fromUserName, String content){
//
//        Image image = Image.builder().prompt(content).n(4).size(size_512.getName()).build();
//
//        ImageResponse response = openAiClient.genImages(image);
//        if (response.getData().size() > 0){
//            String result = response.getData().stream()
//                    .map(o->o.getUrl())
//                    .filter(o-> StringUtils.isNotBlank(o))
//                    .collect(Collectors.joining(","));
//
//            sendKefuMessage(mpService, fromUserName, result);
//        }
//    }

    @Async
    protected WxMpXmlOutMessage replyWithKefuMessageStream(WxMpService mpService, String fromUserName, String content,WxMpXmlMessage wxMessage,
                                              WxMpService weixinService){
        WxMpServiceHttpClientImpl impl;
        List<Message> messages = new ArrayList<>();
        String param = ChatKefuListener.SYSTEM_PRELOAD;
        messages.add(Message.builder().role(Message.Role.SYSTEM).content(param).build());

        //
        Message message = Message.builder().role(Message.Role.USER).content(content).build();
        messages.add(message);

        //客服开始撰写
        try {
            mpService.getKefuService().sendKfTypingState(fromUserName,  "Typing");
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        //开始对话
        String result = questionService.getSysQuestionString(messages);

        log.debug("chatgpt stream done, {}", result);

        if (StringUtils.isBlank(result)){
            redisService.deleteLike(fromUserName);
            return new TextBuilder().build("对话已经重新开始,请输入内容。", wxMessage, weixinService);
        }

        //更新redis
        Message m = Message.builder().role(Message.Role.ASSISTANT).content(result).build();
        messages.add(m);

        //更新redis
//        List temp = new ArrayList(messages);
//
//        for (int i = 0; i < temp.size(); i++) {
//            if (i>0){
//                Map map = JSONObject.parseObject(JSON.toJSONString(temp.get(i)),Map.class);
//                String  contentString = String.valueOf(map.get("content"));
//                if (contentString.length()>99){
//                    temp.remove(i);
//                    i--;
//                }
//            }
//        }
//        if (temp.size() > 6){
//            temp.remove(1);
//        }
//        String json = JSON.toJSONString(temp);
//        redisService.saveValue(fromUserName, json);

        log.debug("update redis result");

        sendKefuMessage(mpService, fromUserName, result);

        //客服结束撰写
        try {
             mpService.getKefuService().sendKfTypingState(fromUserName,  "CancelTyping");
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void sendKefuMessage(WxMpService wxMpService, String fromUserName, String result){
        //发送客服消息
        WxMpKefuMessage kefuMessage = WxMpKefuMessage.TEXT()
                .content(result).toUser(fromUserName).build();

        log.debug("客服消息 message {}:{}", fromUserName, kefuMessage);
        try {
            System.out.println("1 current thread" + Thread.currentThread());
            wxMpService.getKefuService().sendKefuMessage(kefuMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        log.debug("客服消息 finish");
    }
}
